import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
import Vue from "vue"
import UnitechsJs from 'unitechs-js'
// 根据环境不同引入不同api地址
const service = axios.create({
  baseURL: 'http://221.178.123.83:9010', // http://10.227.148.130:9010
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true
      })
    }
    // Toast(`config${JSON.stringify(config)}`)
    if (UnitechsJs.utils.getCookie('zy_token')) {
      config.headers['zy_token'] = UnitechsJs.utils.getCookie('zy_token')
    }
    return config
  },
  error => {
    Toast(`请求接口失败${error}`)
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    loginStatus(response.data)
    const res = response.data
    const data = res.data
    if (res.code && (res.code == 200 || res.code == '0000')) {
      return Promise.resolve(data)
    } else {
      // 登录超时,重新登录
      if (res.status === 401) {
        Toast(`登录超时,重新登录`)
      } else {
        Toast(`接口报错${res.msg},${res.tip}`)
      }
      return Promise.reject(res || 'error')
    }
  },
  error => {
    Toast.clear()
    Toast(`接口返回报错${error}`)
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

function loginStatus(data) {
  if (
    data.code === '409' ||
    (data.data && data.data.code === '409')
  ) {
    Toast('登录验证码失效')
  } else if (data.code === '410' || (data.data && data.data.code === '410')) {
    Toast('验证码输入不正确')
  } else if (data.code === '100204') {
    Toast('当前账号登录失败已达限定次数，账号已锁定')
  } else if (data.code === '100207') {
    Toast('当前账户已过期')
  } else if (data.code === '100202') {
    Toast('当前账号密码已过期')
  } else if (data.code === '100201') {
    Toast('用户名或密码错误')
  }
}

export default service
